package com.tuzhi.filestore.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tuzhi.base.web.helper.AjaxResultHelper;
import com.tuzhi.base.web.util.ControllerUtils;
import com.tuzhi.base.web.vo.AjaxResultVO;
import com.tuzhi.common.constants.ResultConstant;
import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.filestore.http.BillApiClient;
import com.tuzhi.filestore.model.response.Result;
import com.tuzhi.filestore.mq.producter.MsgProducter;
import com.tuzhi.filestore.service.FileUpLogService;
import com.tuzhi.filestore.vo.UpFileRetVo;
import com.tuzhi.vo.bill.FileUpLogVo;
import com.tuzhi.vo.bill.ProcessSampleVo;
import com.tuzhi.vo.bill.UpFileNewOrderRetVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
@Api(description = "加工样板数据")
@Slf4j
@RestController
@RequestMapping("/processSample")
public class ProcessSampleController {

    @Autowired
    FileUpLogService fileService;

    @Autowired
    BillApiClient billApiClient;

    @Autowired
    MsgProducter msgProducter;

    /**
     * 此接口由前端，上传文件创建订单调用
     *
     * @param file          文件流信息
     * @param processSample 创建订单相关的信息
     * @return
     */
    @ApiOperation(value = "创建加工样板数据")
    @PutMapping
    public AjaxResultVO createProcessSample(@ApiParam(name = "file", value = "模型文件", required = true) @RequestParam(name = "file", required = true) MultipartFile file,@ApiParam(name = "processSample", value = "模型记录数据（{\"targetPrice\":1000,\"rmk\":\"test\",\"moduleName\":\"test\"})", required = true) @RequestParam(name = "processSample", required = true) String processSample) {
        log.info("processSample:{}", processSample);
        log.info("file:{}", file);
        AjaxResultVO ajaxResultVO = null;
        try {
            if (file == null) {
                throw new BusinessException("文件不能为空");
            }
            if (StringUtils.isEmpty(processSample)) {
                throw new BusinessException("加工样板信息不能为空");
            }

            ProcessSampleVo processSampleVo = JSONUtil.toBean(processSample, ProcessSampleVo.class, false);
            if (processSampleVo == null) {
                throw new BusinessException("加工样板信息不能为空");
            }

            if (StringUtils.isEmpty(processSampleVo.getModuleName())) {
                processSampleVo.setModuleName(FilenameUtils.getBaseName(file.getOriginalFilename()));
            }
            Result<FileUpLogVo> result = fileService.upLoadOrderModel(file);
            if (!result.isSuccess()) {
                ajaxResultVO = AjaxResultHelper.error();
                ajaxResultVO.setMsg("创建订单失败，原因上传文件失败：-" + result.getDescription());
                return ajaxResultVO;
            }

            String lot = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            FileUpLogVo upLogEntity = result.getData();

            upLogEntity.setUpLot(lot);
            //upLogEntity.setCreatedTime(new Date());
            processSampleVo.setFileUpLogVo(upLogEntity);
            UpFileRetVo retVo = createProcessSampleAndUploadLog(processSampleVo);
            log.info("ccreateProcessSampleAndUploadLog 创建订单返回 ：{}", retVo != null ? new JSONObject(retVo).toString() : "返回空");
            if (retVo.getCode() == 0) {
                ajaxResultVO = AjaxResultHelper.success();
                Message message = new Message(String.format(retVo.getId().toString()).getBytes());
                String upFileType = "cadFile";
                if (upFileType.equalsIgnoreCase(retVo.getMsg())) {
                    msgProducter.sendMsg("topic_task", "parse.convert", message);
                    log.info("发送消息成功！topic_task,parse.convert{}", retVo.getId());
                } else {
                    msgProducter.sendMsg("topic_task", "parse.step", message);
                    log.info("发送消息成功！topic_task,parse.step{}", retVo.getId());
                }
            } else {
                ajaxResultVO = AjaxResultHelper.error();
            }
            ajaxResultVO.setData(retVo);
            return ajaxResultVO;

        } catch (Exception ex) {
            log.warn("上传异常，orderInfo{}-{}", processSample, ExceptionUtils.getRootCauseStackTrace(ex));
            ResultConstant.RC rc = new ResultConstant.RC("uploadFilessErr", ex.getMessage());
            AjaxResultVO ajax = AjaxResultHelper.build(rc);
            return ajax;
        }
    }

    /**
     * 创建订单，并保存文件 日志信息，模型信息     *
     *
     * @param processSampleVo
     * @return
     */
    private UpFileRetVo createProcessSampleAndUploadLog(ProcessSampleVo processSampleVo) {
        log.info("创建加工样板数据，上传日志记录：{}", processSampleVo.toString());
        try {
            log.info("调用BILL 创建加工样板数据 ：{}", ControllerUtils.getToken(null));
            com.tuzhi.base.web.vo.Result<UpFileNewOrderRetVo> resultVO = billApiClient.createProcessSample(JSONUtil.parse(processSampleVo).toString(), ControllerUtils.getToken(null));

            log.info("创建加工样板数据返回 ：{}", JSONUtil.parse(resultVO).toString());
            if (!"0".equalsIgnoreCase(resultVO.getCode())) {
                UpFileRetVo retVo = new UpFileRetVo();
                retVo.setFileName(processSampleVo.getModuleName());
                retVo.setCode(-1);
                retVo.setMsg("创建加工样板数据失败:" + resultVO.getDescription());
                return retVo;
            }
            UpFileNewOrderRetVo upFileNewOrderRetVo = resultVO.getData();

            UpFileRetVo retVo = new UpFileRetVo();
            Long modelId = Long.parseLong(upFileNewOrderRetVo.getId().toString());
            Long orderId = upFileNewOrderRetVo.getOrderId();
            retVo.setId(modelId);
            retVo.setOrderId(orderId);
            retVo.setMsg(upFileNewOrderRetVo.getMsg());
            return retVo;
        } catch (Exception exception) {
            log.warn("创建加工样板数据，上传记录时异常:fileName:{},err:{}", processSampleVo.getFileUpLogVo().getOriginalFileName(), ExceptionUtils.getStackTrace(exception));
            UpFileRetVo retVo = new UpFileRetVo();
            retVo.setFileName(processSampleVo.getFileUpLogVo().getOriginalFileName());
            retVo.setCode(-1);
            retVo.setMsg("创建加工样板数据，保存记录时异常" + ExceptionUtils.getRootCauseMessage(exception));
            return retVo;
        }
    }

    @GetMapping({"/test"})
    public AjaxResultVO test() {
        log.info("心跳接口测试，接口正常");
        AjaxResultVO ajaxResultVO = AjaxResultHelper.success();
        ajaxResultVO.setMsg("心跳接口测试，接口正常:");
        ajaxResultVO.setData(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        return ajaxResultVO;
    }
}
